package service;

import com.mysql.cj.jdbc.JdbcConnection;
import dao.*;
import pojo.Admin;
import pojo.CheckInRecord;
import pojo.CheckOutRecord;
import pojo.PayRecord;
import utils.JDBCUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

public class PayRecordServiceImpl implements PayRecordService{
    private PayRecordDao dao = new PayRecordDaoImpl();
    private Connection connection = null;

    @Override
    public ArrayList<PayRecord> findAll() {
        return dao.findAll();
    }

    @Override
    public ArrayList<PayRecord> findDate(Date begin, Date end) {
        ArrayList<PayRecord> list = dao.findAll();
        ArrayList<PayRecord> payRecords = new ArrayList<PayRecord>();
        for (PayRecord payRecord : list) {
            if((payRecord.getPay_time().after(begin)&&payRecord.getPay_time().before(end))||payRecord.getPay_time().equals(begin)||payRecord.getPay_time().equals(end)){
                payRecords.add(payRecord);
            }
        }
        return payRecords;
    }

    @Override
    public PayRecord findById(Integer payId) {
        return dao.findById(payId);
    }

    @Override
    public int insert(PayRecord payRecord) {
        try {
            connection = JDBCUtils.getConnection();
            connection.setAutoCommit(false);
            //增加缴费记录
            int row1 = dao.insert(connection,payRecord);
            //修改对应表
                //false - 住宿费 -check_in_record 修改 actual_payment
                //true - 押金 -check_in_record 修改 payedCash
            //得到入住记录
            CheckInRecordService cr = new CheckInRecordServiceImpl();
            CheckInRecord checkInRecord = cr.findByStuId(payRecord.getStuId());
            if(payRecord.getRemark()){
                checkInRecord.setPayment(checkInRecord.getPayment().add(payRecord.getPayment()));
            }else checkInRecord.setPayedCash(checkInRecord.getPayedCash().add(payRecord.getPayment()));

            //更改入住信息
            int row2 = cr.update(checkInRecord);
            connection.commit();
            return row2+row1;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            try {
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public int update(PayRecord payRecord) {
        return dao.update(payRecord);
    }

    @Override
    public int delete(Integer payId) {
        return dao.delete(payId);
    }
}
